//
//  SLOptionChooseView.m
//  SulitLoanDemo
//
//  Created by 虞嘉伟 on 2025/2/22.
//

#import "SLOptionChooseView.h"
#import <YYKit.h>
#import <Masonry.h>


@interface SLOptionChooseView ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIImageView *icon;
@property (nonatomic, strong) UIView *content;
@property (nonatomic, strong) UIView *pannel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UIImageView *decorate;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *confirmButton;

@property (nonatomic, assign) NSInteger selectIndex;
@end

@implementation SLOptionChooseView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColorHex(#000000A6);
        
        [self addSubview:self.icon];
        [self addSubview:self.content];
        [self.content addSubview:self.pannel];
        [self.content addSubview:self.bottomView];
        
        [self.pannel addSubview:self.titleLabel];
        [self.pannel addSubview:self.closeButton];
        [self.pannel addSubview:self.decorate];
        [self.pannel addSubview:self.tableView];
        
        [self.bottomView addSubview:self.confirmButton];
        
        [self.icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.content).inset(20);
            make.top.equalTo(self.content).offset(-106);
            make.width.mas_equalTo(164);
            make.height.mas_equalTo(164);
        }];
        [self.content mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.bottom.equalTo(self);
            make.height.mas_equalTo(521);
        }];
        [self.pannel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.content);
        }];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.pannel).inset(12);
            make.top.equalTo(self.pannel).inset(18);
            make.width.mas_equalTo(self.titleLabel.intrinsicContentSize.width+20*2);
            make.height.mas_equalTo(30);
        }];
        [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.pannel).inset(12);
            make.centerY.equalTo(self.titleLabel);
            make.width.height.mas_equalTo(30);
        }];
        [self.decorate mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.pannel);
            make.top.equalTo(self.titleLabel.mas_bottom).offset(10);
            make.height.mas_equalTo(10);
        }];
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.pannel).inset(0);
            make.top.equalTo(self.decorate.mas_bottom).offset(0);
            make.bottom.equalTo(self.pannel).inset(0);
        }];
        [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.content);
            make.top.equalTo(self.pannel.mas_bottom);
            make.height.mas_equalTo(100);
            make.bottom.equalTo(self.content);
        }];
        [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.bottomView).inset(35);
            make.top.equalTo(self.bottomView).offset(11);
            make.height.mas_equalTo(54);
        }];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.content layoutIfNeeded];
    [self.pannel roundTopCornerRadius:20];
}


- (void)setType:(SLOptionChooseViewType)type {
    _type = type;
    if (self.type == SLOptionChooseViewTypeIDCard) {
        self.titleLabel.text = @"Select ID Card";
    } else if (self.type == SLOptionChooseViewTypeInformation) {
        self.titleLabel.text = @"Confirm Information";
    } else {
        self.titleLabel.text = @"Confirm Information";
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.type == SLOptionChooseViewTypeInformation) {
        return 90;
    } else {
        return 80;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.type == SLOptionChooseViewTypeIDCard) {
        SLIDCardOptionChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLIDCardOptionChooseCell" forIndexPath:indexPath];
        cell.isSelected = indexPath.row == self.selectIndex;
        !self.itemViewCallback ?: self.itemViewCallback(cell, indexPath.row);
        return cell;
    } else if (self.type == SLOptionChooseViewTypeInformation) {
        SLInformationOptionChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLInformationOptionChooseCell" forIndexPath:indexPath];
        !self.itemViewCallback ?: self.itemViewCallback(cell, indexPath.row);
        return cell;
    } else {
        SLCommonOptionChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLCommonOptionChooseCell" forIndexPath:indexPath];
        cell.isSelected = indexPath.row == self.selectIndex;
        !self.itemViewCallback ?: self.itemViewCallback(cell, indexPath.row);
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.selectIndex = indexPath.row;
    [tableView reloadData];
}

- (UIImageView *)icon {
    if (!_icon) {
        _icon = [UIImageView new];
        _icon.contentMode = UIViewContentModeScaleAspectFit;
        _icon.image = [UIImage imageNamed:@"icon_start_auth"];
    }
    return _icon;
}

- (UIView *)content {
    if (!_content) {
        _content = [UIView new];
    }
    return _content;
}
- (UIView *)pannel {
    if (!_pannel) {
        _pannel = [UIView new];
        _pannel.backgroundColor = UIColor.whiteColor;
        _pannel.layer.cornerRadius = 20;
    }
    return _pannel;
}
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.text = @"Confirm Information";
        _titleLabel.font = aspectDefaultFont(16);
        _titleLabel.backgroundColor = UIColorHex(#1B1B1B);
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = UIColor.whiteColor;
        _titleLabel.layer.masksToBounds = YES;
        _titleLabel.layer.cornerRadius = 15;
    }
    return _titleLabel;
}
- (UIButton *)closeButton {
    if (!_closeButton) {
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton setImage:[UIImage imageNamed:@"icon_close"] forState:UIControlStateNormal];
        [_closeButton addTarget:self action:@selector(closeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeButton;
}
- (UIImageView *)decorate {
    if (!_decorate) {
        _decorate = [UIImageView new];
        _decorate.backgroundColor = UIColorHex(#FDC5E0);
    }
    return _decorate;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:SLCommonOptionChooseCell.class forCellReuseIdentifier:@"SLCommonOptionChooseCell"];
        [_tableView registerClass:SLIDCardOptionChooseCell.class forCellReuseIdentifier:@"SLIDCardOptionChooseCell"];
        [_tableView registerClass:SLInformationOptionChooseCell.class forCellReuseIdentifier:@"SLInformationOptionChooseCell"];
    }
    return _tableView;
}
- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [UIView new];
        _bottomView.backgroundColor = UIColorHex(#FDC5E0);
    }
    return _bottomView;
}
- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setTitle:@"Confirm" forState:UIControlStateNormal];
        [_confirmButton setImage:[UIImage imageNamed:@"btn_more_white"] forState:UIControlStateNormal];
        [_confirmButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_confirmButton jk_setImagePosition:LXMImagePositionRight spacing:10];
        _confirmButton.backgroundColor = UIColorHex(#1B1B1B);
        _confirmButton.titleLabel.font = aspectDefaultFont(16);
        _confirmButton.layer.cornerRadius = 20;
        _confirmButton.layer.borderColor = UIColorHex(#1B1B1B).CGColor;
        _confirmButton.layer.borderWidth = 1;
        [_confirmButton addTarget:self action:@selector(confirmButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

#pragma mark - 点击事件
- (void)dismiss {
    [self removeFromSuperview];
}
- (void)closeButtonAction:(UIButton *)button {
    [self dismiss];
}

- (void)confirmButtonAction:(UIButton *)button {
    !self.confirmButtonCallback ?: self.confirmButtonCallback(self.selectIndex);
}

- (void)dealloc {
    NSLog(@"---> %@ Dealloc", NSStringFromClass(self.class));
    [NSNotificationCenter.defaultCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [NSNotificationCenter.defaultCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
@end


@implementation SLOptionChooseView (Fast)

/// Common类型选择弹窗
/// - Parameters:
///   - count: 数量
///   - itemViewCallback: 视图回调
///   - confirmButtonCallback: 确认按钮点击回调
+ (instancetype)showOptionCommonChooseWithCount:(NSInteger)count itemViewCallback:(void(^)(SLCommonOptionChooseCell *item, NSInteger index))itemViewCallback confirmCallback:(void(^)(NSInteger index))confirmButtonCallback {
    
    SLOptionChooseView *alert = [SLOptionChooseView new];
    @weakify(alert);
    [alert showOptionCommonChooseWithCount:count itemViewCallback:itemViewCallback confirmCallback:^(NSInteger index) {
        @strongify(alert);
        !confirmButtonCallback ?: confirmButtonCallback(index);
        [alert dismiss];
    }];
    
    return alert;
}

- (void)showOptionCommonChooseWithCount:(NSInteger)count itemViewCallback:(void(^)(SLCommonOptionChooseCell *item, NSInteger index))itemViewCallback confirmCallback:(void(^)(NSInteger index))confirmButtonCallback {
    
    self.type = SLOptionChooseViewTypeCommon;
    self.count = count;
    self.itemViewCallback = itemViewCallback;
    self.confirmButtonCallback = confirmButtonCallback;
    [UIApplication.sharedApplication.keyWindow addSubview:self];
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.superview);
    }];
}



/// IDCard类型选择弹窗
/// - Parameters:
///   - count: 数量
///   - itemViewCallback: 视图回调
///   - confirmButtonCallback: 确认按钮点击回调
+ (instancetype)showOptionIDCardChooseWithCount:(NSInteger)count itemViewCallback:(void(^)(SLIDCardOptionChooseCell *item, NSInteger index))itemViewCallback confirmCallback:(void(^)(NSInteger index))confirmButtonCallback {
    
    SLOptionChooseView *alert = [SLOptionChooseView new];
    @weakify(alert);
    [alert showOptionIDCardChooseWithCount:count itemViewCallback:itemViewCallback confirmCallback:^(NSInteger index) {
        @strongify(alert);
        !confirmButtonCallback ?: confirmButtonCallback(index);
        [alert dismiss];
    }];
    
    return alert;
}

- (void)showOptionIDCardChooseWithCount:(NSInteger)count itemViewCallback:(void(^)(SLIDCardOptionChooseCell *item, NSInteger index))itemViewCallback confirmCallback:(void(^)(NSInteger index))confirmButtonCallback {
    
    self.type = SLOptionChooseViewTypeIDCard;
    self.count = count;
    self.itemViewCallback = itemViewCallback;
    self.confirmButtonCallback = confirmButtonCallback;
    [UIApplication.sharedApplication.keyWindow addSubview:self];
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.superview);
    }];
    
}


/// Information类型选择弹窗
/// - Parameters:
///   - count: 数量
///   - itemViewCallback: 视图回调
///   - confirmButtonCallback: 确认按钮点击回调
+ (instancetype)showOptionInformationChooseWithCount:(NSInteger)count itemViewCallback:(void(^)(SLInformationOptionChooseCell *item, NSInteger index))itemViewCallback confirmCallback:(void(^)(NSInteger index))confirmButtonCallback {
    
    SLOptionChooseView *alert = [SLOptionChooseView new];
    @weakify(alert);
    [alert showOptionInformationChooseWithCount:count itemViewCallback:itemViewCallback confirmCallback:^(NSInteger index) {
        @strongify(alert);
        !confirmButtonCallback ?: confirmButtonCallback(index);
        [alert dismiss];
    }];
    
    return alert;
}

- (void)showOptionInformationChooseWithCount:(NSInteger)count itemViewCallback:(void(^)(SLInformationOptionChooseCell *item, NSInteger index))itemViewCallback confirmCallback:(void(^)(NSInteger index))confirmButtonCallback {
    self.type = SLOptionChooseViewTypeInformation;
    self.count = count;
    self.itemViewCallback = itemViewCallback;
    self.confirmButtonCallback = confirmButtonCallback;
    [UIApplication.sharedApplication.keyWindow addSubview:self];
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.edges.equalTo(self.superview);
        make.left.right.equalTo(self.superview);
        make.height.mas_equalTo(self.superview);
        make.bottom.equalTo(self.superview);
    }];
    
    // 添加键盘通知观察者
    [NSNotificationCenter.defaultCenter addObserverForName:UIKeyboardWillShowNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
        // 获取键盘高度
        CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat keyboardHeight = keyboardFrame.size.height;
        
        // 获取动画持续时间
        NSTimeInterval duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        
        // 在这里处理键盘弹出逻辑
        NSLog(@"键盘弹出，高度: %f, 动画时间: %f", keyboardHeight, duration);
        
        UIView *responder = [self findFirstResponderInView:self];
        if (!responder) return;
        
        // 计算输入框需要移动的距离
        CGRect textFieldFrame = [responder.superview convertRect:responder.superview.bounds toView:self];
        CGFloat offset = CGRectGetMaxY(textFieldFrame) - CGRectGetMinY(keyboardFrame);
        
        if (offset > 0) {
            // 如果需要动画同步
            [UIView animateWithDuration:duration animations:^{
                // 更新UI布局
                [self mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(self.superview).inset(offset);
                }];
                [self.superview layoutIfNeeded];
            }];
        }
    }];

    [NSNotificationCenter.defaultCenter addObserverForName:UIKeyboardWillHideNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
        // 获取动画持续时间
        NSTimeInterval duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        
        // 在这里处理键盘收起逻辑
        NSLog(@"键盘收起");
        
        [UIView animateWithDuration:duration animations:^{
            // 恢复UI布局
            [self mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.superview);
            }];
            [self.superview layoutIfNeeded];
        }];
    }];
}

- (UIView *)findFirstResponderInView:(UIView *)view {
    if ([view isFirstResponder]) {
        return view;
    }
    for (UIView *subview in view.subviews) {
        UIView *responder = [self findFirstResponderInView:subview];
        if (responder) {
            return responder;
        }
    }
    return nil;
}

@end
